package com.yangaobo.mapper;

import com.yangaobo.dto.DeptPageDTO;
import com.yangaobo.entity.Dept;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 杨奥博
 */
@Repository
public interface DeptMapper {
    @Insert("""
            insert into ums_dept(`title`, `fk_room_id`, `info`, `deleted`, `version`, `created`, `updated`)
            values (#{title}, #{fkRoomId}, #{info}, #{deleted}, #{version}, #{created}, #{updated})
            """)
    int insert(Dept dept);

    @Results(
            id = "deptResultMap",
            value = {
                    @Result(property = "id",column = "id",id = true),
                    @Result(property = "fkRoomId",column = "fk_room_id"),
                    @Result(property = "room",column = "fk_room_id",one = @One(select = "com.yangaobo.mapper.RoomMapper.select")),
            }
    )
    @Select("""
            select * from ums_dept t where t.id = #{param1} and t.deleted = 0
            """)
    Dept select(Long id);

    @ResultMap("deptResultMap")
    @Select("""
            <script>
            select * from ums_dept t
           <where>
                <if test='title != null'> title like concat('%', #{title}, '%') and </if>
                <if test='fkRoomId != null'> fk_room_id = #{fkRoomId} and </if>
                t.deleted = 0
            </where>
            </script>
            """)
    List<Dept> list(DeptPageDTO dto);

    @Update("""
            <script>
            update ums_dept
            <set>
                <if test="title != null">title = #{title},</if>
                <if test="fkRoomId != null">fk_room_id = #{fkRoomId},</if>
                <if test="info != null">info = #{info},</if>
                <if test="deleted != null">deleted = #{deleted},</if>
                <if test="created != null">created = #{created},</if>
                <if test="updated != null">updated = #{updated},</if>
                version=version+1
            </set>
            where id = #{id} and deleted = 0 and version = #{version}
            </script>
            """
            )
    int update(Dept dept);

    @Update("""
            update ums_dept set deleted = 1, updated = current_timestamp where id = #{id}
            """)
    int delete(Long id);

    @Update("""
            <script>
            update ums_dept set deleted = 1, updated = current_timestamp where
            <foreach collection='list' item='e' open='id in (' close= ')' separator=','>
                #{e}
            </foreach>
            </script>
            """)
    int deleteBatch(List<Long> ids);

}
